//
//  GQHRegisterView.m
//  Xanthium
//
//  Created by GuanQinghao on 22/02/2018.
//  Copyright © 2018 GuanQinghao. All rights reserved.
//

#import "GQHRegisterView.h"
#import "GQHHeader.h"
#import "GQHBaseModel.h"

@interface GQHRegisterView () <UITextFieldDelegate> {
    
    // 获取验证码按钮
    UIButton *codeButton;
    // 下一步按钮
    UIButton *nextButton;
    
    // 手机号输入框
    UITextField *mobileTextField;
    // 验证码输入框
    UITextField *codeTextField;
}

@end

@implementation GQHRegisterView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = kClearColor;
        
        [self loadLocalData];
        [self loadUserInterface];
    }
    return self;
}

#pragma mark --Data
- (void)loadLocalData {
    
}

#pragma mark --View
- (void)loadUserInterface {
    
    UIView *containerView = [[UIView alloc] init];
    containerView.layer.cornerRadius = 5.0;
    containerView.layer.masksToBounds = YES;
    containerView.backgroundColor = [UIColor whiteColor];
    [self addSubview:containerView];
    [containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self).with.offset(GQH_MARGIN_SINGLE);
        make.right.mas_equalTo(self).with.inset(GQH_MARGIN_SINGLE);
        make.top.mas_equalTo(self).with.offset(10);
        make.height.mas_equalTo(120);
    }];
    
    UIImageView *phoneImageView = [[UIImageView alloc] init];
    phoneImageView.image = [UIImage imageNamed:@"login_phone"];
    [containerView addSubview:phoneImageView];
    [phoneImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.and.top.and.width.and.height.mas_equalTo(20);
    }];
    
    mobileTextField = [[UITextField alloc] init];
    mobileTextField.placeholder = @"手机号";
    mobileTextField.delegate = self;
    mobileTextField.keyboardType = UIKeyboardTypeNumberPad;
    [containerView addSubview:mobileTextField];
    [mobileTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(phoneImageView.mas_right).with.offset(20);
        make.right.mas_equalTo(containerView).with.inset(20);
        make.height.mas_equalTo(30);
        make.centerY.mas_equalTo(phoneImageView);
    }];
    
    UIView *splitView = [[UIView alloc] init];
    splitView.layer.cornerRadius = 1.0;
    splitView.layer.masksToBounds = YES;
    splitView.backgroundColor = kLightGrayColor;
    [containerView addSubview:splitView];
    [splitView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(containerView).with.offset(20);
        make.right.mas_equalTo(containerView).with.inset(20);
        make.center.mas_equalTo(containerView);
        make.height.mas_equalTo(1);
    }];
    
    UIImageView *passwordImageView = [[UIImageView alloc] init];
    passwordImageView.image = [UIImage imageNamed:@"login_password"];
    [containerView addSubview:passwordImageView];
    [passwordImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.and.width.and.height.mas_equalTo(20);
        make.top.mas_equalTo(splitView.mas_bottom).with.inset(20);
    }];
    
    codeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    codeButton.backgroundColor = kWhiteColor;
    codeButton.layer.cornerRadius = 5.0;
    codeButton.layer.borderWidth = 1.0;
    codeButton.layer.borderColor = kGrayColor.CGColor;
    codeButton.layer.masksToBounds = YES;
    codeButton.titleLabel.font = kDefaultFont;
    codeButton.userInteractionEnabled = NO;
    [codeButton setTitle:@"验证码" forState:UIControlStateNormal];
    [codeButton setTitleColor:kGrayColor forState:UIControlStateNormal];
    [codeButton addTarget:self action:@selector(startCountingDown:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:codeButton];
    [codeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.mas_equalTo(passwordImageView);
        make.right.mas_equalTo(containerView).with.inset(20);
        make.height.mas_equalTo(44);
        make.width.mas_equalTo(100);
    }];
    
    codeTextField = [[UITextField alloc] init];
    codeTextField.placeholder = @"验证码";
    codeTextField.keyboardType = UIKeyboardTypeNumberPad;
    [containerView addSubview:codeTextField];
    [codeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(passwordImageView.mas_right).with.offset(20);
        make.right.mas_equalTo(codeButton.mas_left);
        make.height.mas_equalTo(30);
        make.centerY.mas_equalTo(passwordImageView);
    }];
    
    nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    nextButton.backgroundColor = kWhiteColor;
    nextButton.layer.cornerRadius = 5.0;
    nextButton.layer.masksToBounds = YES;
    [nextButton setTitle:@"下一步" forState:UIControlStateNormal];
    [nextButton setTitleColor:kAppRedColor forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(setupPassword:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:nextButton];
    [nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.and.right.mas_equalTo(containerView);
        make.top.mas_equalTo(containerView.mas_bottom).with.offset(10);
        make.height.mas_equalTo(44);
    }];
    
    CGSize textSize = [GQHBaseModel sizeWithString:@"《云交智云平台服务协议》" font:[UIFont systemFontOfSize:15] maxSize:CGSizeMake(self.qh_width, 20)];
    UIButton *agreementButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [agreementButton setTitle:@"《云交智云平台服务协议》" forState:UIControlStateNormal];
    [agreementButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [agreementButton addTarget:self action:@selector(checkAgreement:) forControlEvents:UIControlEventTouchUpInside];
    agreementButton.titleLabel.font = [UIFont systemFontOfSize:15];;
    [self addSubview:agreementButton];
    [agreementButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(textSize.width, 20));
        make.centerX.mas_equalTo(self);
        make.bottom.mas_equalTo(self.mas_bottom).with.inset(50);
    }];
    
    UIButton *checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
    checkButton.backgroundColor = [UIColor whiteColor];
    checkButton.layer.cornerRadius = 3.0;
    checkButton.layer.borderWidth = 1.0;
    checkButton.layer.borderColor = kAppRedColor.CGColor;
    checkButton.layer.masksToBounds = YES;
    checkButton.selected = YES;
    [checkButton setImage:[UIImage imageNamed:@"login_register_agreement"] forState:UIControlStateSelected];
    [checkButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [checkButton addTarget:self action:@selector(agreeWithAgreement:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:checkButton];
    [checkButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(20, 20));
        make.centerY.mas_equalTo(agreementButton);
        make.right.mas_equalTo(agreementButton.mas_left);
    }];
}

- (IBAction)agreeWithAgreement:(UIButton *)sender {
    DLog(@"选中同意协议内容");
    
    sender.selected = !sender.selected;
    if (sender.selected) {
        
        nextButton.userInteractionEnabled = YES;
        [nextButton setTitleColor:kAppRedColor forState:UIControlStateNormal];
    } else {
        
        nextButton.userInteractionEnabled = NO;
        [nextButton setTitleColor:kGrayColor forState:UIControlStateNormal];
    }
}

- (IBAction)checkAgreement:(UIButton *)sender {
    DLog(@"查看协议内容");
    
    if ([_qh_delegate respondsToSelector:@selector(qh_checkAgreement)]) {
        
        [_qh_delegate qh_checkAgreement];
    }
}

- (IBAction)setupPassword:(UIButton *)sender {
    DLog(@"验证手机号和验证码，成功后跳转设置登陆密码页面");
    
    NSString *mobile = mobileTextField.text;
    NSString *code = codeTextField.text;
    
    if (mobile.length > 1 && code.length > 1) {
        
        if ([_qh_delegate respondsToSelector:@selector(qh_registerWithMobile:code:)]) {
            
            [_qh_delegate qh_registerWithMobile:mobile code:code];
        }
    } else {
        
        [self showToastWithText:@"请输入手机号或验证码"];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *inputString = [mobileTextField.text stringByReplacingCharactersInRange:range withString:string];
    
    if ([inputString qh_isValidMobile]) {
        
        mobileTextField.text = inputString;
        codeButton.userInteractionEnabled = YES;
        codeButton.layer.borderColor = kAppRedColor.CGColor;
        [codeButton setTitleColor:kAppRedColor forState:UIControlStateNormal];
        
        return NO;
    } else {
        
        codeButton.userInteractionEnabled = NO;
        codeButton.layer.borderColor = kGrayColor.CGColor;
        [codeButton setTitleColor:kGrayColor forState:UIControlStateNormal];
        
        return YES;
    }
}

// 验证码倒计时
- (IBAction)startCountingDown:(UIButton *)sender {
    DLog(@"验证码倒计时");
    
    NSString *mobile = mobileTextField.text;
    if ([_qh_delegate respondsToSelector:@selector(qh_requestCodeWithMobile:)]) {
        
        [_qh_delegate qh_requestCodeWithMobile:mobile];
        
        __block NSInteger time = 59;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
        dispatch_source_set_event_handler(timer, ^{
            if (time <= 0) {
                dispatch_source_cancel(timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [codeButton setTitle:@"重新发送" forState:UIControlStateNormal];
                    [codeButton setTitleColor:kAppRedColor forState:UIControlStateNormal];
                    codeButton.userInteractionEnabled = YES;
                    mobileTextField.userInteractionEnabled = YES;
                });
            } else {
                int seconds = time % 60;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [codeButton setTitle:[NSString stringWithFormat:@"重新发送(%.2d)", seconds] forState:UIControlStateNormal];
                    [codeButton setTitleColor:kAppRedColor forState:UIControlStateNormal];
                    codeButton.userInteractionEnabled = NO;
                    mobileTextField.userInteractionEnabled = NO;
                });
                time--;
            }
        });
        dispatch_resume(timer);
    }
}

@end
